注册 登录
编程论坛 C++教室

这个怎么错了 我刚刚学到类~

asd6791868 发布于 2008-10-28 20:25, 1110 次点击
首先谢谢各位大虾百忙之中来找错!~

#include "iostream"

using namespace std;

class print{

public:

    void setp(int);
  
    void p();

private:
 
    int a;
};


void print::setp(int w)
{   
    a=w;
}

void print::p()
{
    cout<<"hello my c++"<<endl;
}

void main()
{  
    
    print b;
    
    b.setp(33);
    
    cout<<b<<endl;
    
    b.print();
    

}
11 回复
#2
youhm2008-10-28 20:37
cout<<b<<endl;
这个对象不能直接输出吧

b.print();
这个对象没有print成员,应是b.p();吧
#3
newyj2008-10-28 20:54
要重载<<为类的友员
friend ostream& operator<<(ostream& out,print& k)
{
  return out<<k.a<<endl;
}
#4
lpf112301082008-10-28 20:59
cout<<b<<endl;
你是想输出对象b中的a吗
#5
asd67918682008-10-28 21:03
只要这个程序能正常运行就行。。。
我想看看我 自己理解的 于正确的有什么不同、。。。
#6
tls4113232008-10-28 22:45
fkjfk
可以加入构造函数利用构造函数给a进行初始化
#7
牧人2008-10-28 23:02
不懂
#8
asd67918682008-10-29 08:28
还是没人告诉我 哪出错了???
#9
newyj2008-10-29 12:34
首先 不能输出一个类对象 cout<<b<<endl
所以要 重载<<运算符
还有b.print();改成b.p();

程序代码:
#include <iostream>
using namespace std;

class print{

public:

    void setp(int);
  
    void p();
    friend ostream& operator<<(ostream& out,print& k)
    {
       return out<<k.a<<endl;
    }

private:

    int a;
};


void print::setp(int w)
{   
    a=w;
}

void print::p()
{
    cout<<"hello my c++"<<endl;
}

int main()
{  
   
    print b;
   
    b.setp(33);
   
    cout<<b<<endl;
   
    b.p();
    return 0;

}
#10
shmilytong2008-10-31 13:09
cout<<b<<endl;错在这一句
#11
pm58062362008-10-31 22:05
楼上的说的不错,还有那个b.print(),应该是想输出b.p()
#12
ling1212112008-10-31 22:28
cout<<b<<endl;错了,你可以设置类的属性成员为public,然后用cout<<b.a<<endl;
也可以在类中定义一个输出函数;
如:
void show()
{
    cout<<a;
}
然后在main() 函数中用cout<<b.show()来实现你想用cout<<b<<endl实现的输出.
1