C++ 一个很初级的有关问题 成员函数为什么会出错
C++ 一个很初级的问题 成员函数为什么会出错
我寒假在家刚开始自学C++,看了一点书,在电脑上(VC 6.0)练习时,出了好几个错误
程序如下:
#include <iostream.h>
class Sample
{
int n,
public:
void setvalue(int m)
{
n=m;
}
void disp()
{
cout < < "n= " < <n < <endl;
}
};
void main()
{
Sample *ps;
ps=new Sample;
ps-> setvalue(10);
ps-> disp();
}
错误有:
error C2059: syntax error : 'public '
error C2039: 'setvalue ' : is not a member of 'Sample '
see declaration of 'Sample '
error C2039: 'disp ' : is not a member of 'Sample '
类Sample中只显示有n这个变量,不知为什么不能用到public声明的成员函数呢?谢谢大家了。
------解决方案--------------------
应将程序修改为:
#include <iostream.h>
class Sample
{
int n; //修改的语句
public:
void setvalue(int m)
{
n=m;
}
void disp()
{
cout < < "n= " < <n < <endl;
}
};
void main()
{
Sample *ps;
ps=new Sample;
ps-> setvalue(10);
ps-> disp();
delete ps; //增加的语句,以防止“内存泄露”。
}
我寒假在家刚开始自学C++,看了一点书,在电脑上(VC 6.0)练习时,出了好几个错误
程序如下:
#include <iostream.h>
class Sample
{
int n,
public:
void setvalue(int m)
{
n=m;
}
void disp()
{
cout < < "n= " < <n < <endl;
}
};
void main()
{
Sample *ps;
ps=new Sample;
ps-> setvalue(10);
ps-> disp();
}
错误有:
error C2059: syntax error : 'public '
error C2039: 'setvalue ' : is not a member of 'Sample '
see declaration of 'Sample '
error C2039: 'disp ' : is not a member of 'Sample '
类Sample中只显示有n这个变量,不知为什么不能用到public声明的成员函数呢?谢谢大家了。
------解决方案--------------------
应将程序修改为:
#include <iostream.h>
class Sample
{
int n; //修改的语句
public:
void setvalue(int m)
{
n=m;
}
void disp()
{
cout < < "n= " < <n < <endl;
}
};
void main()
{
Sample *ps;
ps=new Sample;
ps-> setvalue(10);
ps-> disp();
delete ps; //增加的语句,以防止“内存泄露”。
}