糊涂了,C++类中函数怎么互相传值。。

a294392285 2009-11-30 03:21:35
#include<iostream>
using namespace std;
class Rect//矩阵类
{
private:
const int i=2;//行
const int j=3;//列
// int a[i][j];//这个数组怎么构造
public:
Rect()
{

}
void input()
{ int a=0,b=0;
for(a=0;a<=i;a++)
for(b=0;b<=j;b++)
{
cout<<"please input number";
cin>>a[i][j];
}
}
void show()
{ int a=0,b=0;
for(a=0;b<=i;a++)
for(b=0;b<=j;b++)
cout<<a[i][j];
}
};
void main()
{
Rect A(,);
A.input ();
A.show();
}

类中的共有函数间互相传值是怎么进行的?
...全文
240 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
sduxiaoxiang 2009-12-02
  • 打赏
  • 举报
回复
成员变量就可以了
dqdx_zch 2009-12-02
  • 打赏
  • 举报
回复
那个数组是不是还要在构造函数中初始化啊?
icansaymyabc 2009-12-02
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 a294392285 的回复:]
小弟,不懂为什么要定义成静态的成员,常成员不行么?
老师说定义为静态成员不符合类的要求了。

原本是用来求矩阵相乘的,想定义一个类来,这个矩阵的大小应该可以自由改变,可是这样一来就不能改变了。
[/Quote]


class T {
const int i;
};

class 内部的 const 型其实也是变量,不过是被限定了不可重新赋值的变量。

其实你的
class T{
const int i=3;
};
这样的写法是违反C++标准的,仅有部分不严谨的编译器允许这样做。
真正符合标准的做法是这样的:

class T{
const int i;
public:
T():i(3){}
T(int v):i(v){}
};
可见针对同一个类,不同的实例可以有不同的 i 值,i实际上是一个变量。而数组的申明里不得用变量为下标。只有 static const int i=3; 这才是真正的常量,可用于数组申明。

如果你要随时改变矩阵的大小,请自行搜索“C语言动态2维数组”,一搜一大把。

a294392285 2009-11-30
  • 打赏
  • 举报
回复
小弟,不懂为什么要定义成静态的成员,常成员不行么?
老师说定义为静态成员不符合类的要求了。

原本是用来求矩阵相乘的,想定义一个类来,这个矩阵的大小应该可以自由改变,可是这样一来就不能改变了。
nwao7890 2009-11-30
  • 打赏
  • 举报
回复
楼主可以用宏来解决问题

#include "stdafx.h"
#include <iostream>
using namespace std;

#define row 2
#define col 3

class Rect//矩阵类
{
private:
int m[row][col];//这个数组怎么构造
public:
Rect()
{

}
void input()
{ int a=0,b=0;
for(a=0;a <row;a++)
for(b=0;b <col;b++)
{
cout <<"please input number";
cin>>m[a][b];
}
}
void show()
{ int a=0,b=0;
for(a=0;a <row;a++)
for(b=0;b <col;b++)
cout <<m[a][b];
}
};
void main()
{
Rect A;
A.input();
A.show();
}
swbchangle 2009-11-30
  • 打赏
  • 举报
回复
为什么要传值?
类的成员变量,可以被类的成员函数访问。
input将数据写入数组a,show从数组a读取了数据。实现了传值的效果
wjjjhsxl 2009-11-30
  • 打赏
  • 举报
回复
class Rect//矩阵类
{
private:
static const int i;//行
static const int j;//列
}
const int i=2;
const int j=3;
starix_cai 2009-11-30
  • 打赏
  • 举报
回复
1. i 和 j 应该定义为 static const int 类型的
2. 赋值和显示函数的循环有问题。

#include <iostream>
using namespace std;

class Matrix
{
private:
static const int i = 2;
static const int j = 3;
int array[i][j];
public:
void fill()
{
cout<<"Please fulfill matrix:"<<endl;
for(int row = 0; row < i; row++)
for(int col = 0; col < j; col++)
{
cout<<"Please input array["<<row<<"]["<<col<<"]:\n";
cin>>array[row][col];
}
}
void display()
{
cout<<"Display matrix:"<<endl;
for(int row = 0; row < i; row++)
for(int col = 0; col < j; col++)
cout<<array[row][col]<<(col == j - 1 ? "\n" : "\t");
}
};

int main()
{
Matrix m;
m.fill();
m.display();
}

64,650

社区成员

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

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