我正在学习 c++ 中的类和对象,并尝试了以下代码来测试我是否正确理解它:
#include <iostream>
using namespace std;
class class1
{
public:
void write(int x)
{
dataObject.var = x;
}
};
class class2
{
public:
void read()
{
std::cout << dataObject.var;
}
};
class data
{
public:
int var;
data()
{
var = 1;
}
};
int main()
{
data dataObject;
class1 object1;
class2 object2;
object2.read(data dataObject);
object1.write(2);
object2.read(data dataObject);
return 0;
}
这是两个对象都用于修改和使用第三个的成员,但我收到以下错误:
In member function 'void class1::write(int)':
line 10: error: 'dataObject' was not declared in this scope
In member function 'void class2::read()':
line 14: error: 'dataObject' was not declared in this scope
In function 'int main()':
line 40 + 42: error: expected primary-expression before 'dataObject'
知道我哪里出错了吗?提前致谢。
编辑:感谢所有建议。我现在的代码是:
#include <iostream>
using namespace std;
class class1
{
public:
void write(data &dataObject, int x)
{
dataObject.var = x;
}
};
class class2
{
public:
void read(data dataObject)
{
std::cout << dataObject.var << endl;
}
};
class data
{
public:
int var;
data()
{
var = 1;
}
};
int main()
{
data dataObject;
class1 object1;
class2 object2;
object2.read(dataObject);
object1.write(dataObject,2);
object2.read(dataObject);
return 0;
}
我现在得到错误:
8 错误:“数据”尚未声明
10 错误:在“dataObject”中请求成员“var”,它是非类类型“int”
18 错误:“数据”尚未声明
20 错误:请求“dataObject”中的成员“var”,它是非类类型“int”
40 错误:“dataObject”未在此范围内声明