原来一直有个误区,对象不能直接访问该类成员私有变量,其实是不能在该类的类外访问,在类里还是可以的,和类成员函数一样,在类里都能访问私有变量,在类外不行。看如下代码:

#include <iostream>
#include <memory>
#include <string>
using namespace std;
int g_constructNum = 0;
int g_copyConstructNum = 0;
int g_moveConstructNum = 0;
int g_deleteNum = 0;

class MyTestString
{
private:
    std::string m_data;
    int m_value;
    void test() {}
public:
    MyTestString(std::string data,int value) :m_data(data),m_value(value)
    {
        std::cout << "construct: " << ++g_constructNum << std::endl;
    }
    MyTestString(const MyTestString& myTestString)
    {
        m_data = myTestString.m_data;
        m_value = myTestString.m_value;
        std::cout << "copy construct: " << ++g_copyConstructNum << std::endl;
    }
    MyTestString(MyTestString &&myTestString)
    {
        std::swap(m_data, myTestString.m_data);
        std::swap(m_value, myTestString.m_value);
        std::cout << "move copy construct: " << ++g_moveConstructNum << std::endl;
    }
    ~MyTestString()
    {
        std::cout << "destruct: " << ++g_deleteNum << std::endl;
    }
};

MyTestString getTempString()
{
    MyTestString temp("tangmiao", 1);
    return temp;
}

int main()
{
    //MyTestString temp = getTempString();
    //MyTestString temp(MyTestString("tangmiao",1));
    MyTestString temp("tangmiao");
    temp.m_data;//1
    return 0;
}

导致编译出错的地方是1而不是类里面的其他地方。想在类外访问私有变量就要类提供接口了。