初学C++ 类和友元,我真的不知道是怎么错了。。。

Crazy_hand 2009-10-11 05:41:42

/*
12.38 定义一个命名为Foo的类,具有单个int型数据成员。为该类定义一个构造函数,
接受一个int值并用该值初始化数据成员。为该类定义一个函数,返回其数据成员
的值。

12.39 给定上题中定义的Foo类定义另一个Bar类。Bar类具有两个static数据成员:一个
为int型,另一个为Foo类型。

12.40 使用上面两题中定义的类,给Bar类增加一对成员:第一个成员命名为FooVal,返回
Bar类的Foo类型static成员的值;第二个成员命名为callsFooVal,保存FooVal被调用
的次数。
*/

#include <iostream>
#include <cstdlib>

using namespace std;
//12.38
class Foo {
public:
int riten_val( ) const { return Foo_i; }

Foo( int a ):Foo_i(a)
{
//The body is NULL;
}

private:
int Foo_i;
};
//12.39
class Bar {
public:
//////12.40
Foo& FooVal( ) const;
int callsFooVal( ) const { ++Bar_i; }
friend void display( ostream& outt, Bar& te);

Bar( )
{
//The body is NULL;
}

private:
static int Bar_i;
static Foo FooInBar;

};

Foo& Bar::FooVal( ) const
{
callsFooVal();
return FooInBar;
}

int Bar::Bar_i( 0 );
Foo Bar::FooInBar( 0 );

//两个错误,都指向这里。。。编译器VS2008_Win7
void display( ostream& outt, Bar& te )// 缺少“,”(在标识符“)”的前面); 语法错误 : 缺少“)”(在“{”的前面)
{
outt << te.FooInBar.riten_val( ) << " " << te.Bar_i << endl;
}


int main( void )
{
Bar temp;
for( int i=0; i!=10; ++i )
{
temp.FooVal( );
display( cout, temp );
}
system( "pause" );
return 0;
}

...全文
151 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
wxdcxp 2009-10-11
  • 打赏
  • 举报
回复

void display( ostream& outt, Bar& te )

楼主太不小心啦,右边刮号跟左边的字体不一样看出来了吗
na2650945 2009-10-11
  • 打赏
  • 举报
回复

#include <iostream>
#include <cstdlib>

using namespace std;
//12.38
class Foo {
public:
int riten_val( ) const { return Foo_i; }

Foo( int a ):Foo_i(a)
{
//The body is NULL;
}

private:
int Foo_i;
};
//12.39
class Bar {
public:
//////12.40
Foo& FooVal( ) const;
int callsFooVal( ) const { ++Bar_i; }//没有返回值。要么return
//要么void callsFooVal()
friend void display( ostream& outt, Bar& te);

Bar( )
{
//The body is NULL;
}

private:
static int Bar_i;
static Foo FooInBar;

};

Foo& Bar::FooVal( ) const
{
callsFooVal();
return FooInBar;
}

int Bar::Bar_i( 0 );
Foo Bar::FooInBar( 0 );

//两个错误,都指向这里。。。编译器VS2008_Win7
void display( ostream& outt, Bar& te )// 括号用错了。用的是中文下的括号吧。
{
outt << te.FooInBar.riten_val( ) << " " << te.Bar_i << endl;
}


int main( void )
{
Bar temp;
for( int i=0; i!=10; ++i )
{
temp.FooVal( );
display( cout, temp );
}
system( "pause" );
return 0;
}
wanjingwei 2009-10-11
  • 打赏
  • 举报
回复
int callsFooVal( ) const { ++Bar_i; }
没有返回值
baihacker 2009-10-11
  • 打赏
  • 举报
回复
void display( ostream& outt, Bar& te )

你用的是全角的
而不是半角的)

64,653

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧