为什么下面的C++代码会给出这样的输出
Why the following C++ code gives this output?
我正在尝试在c++中学习Operator Overloading
。我正在使用Operator Overloading
概念添加两个矩阵。我正在使用语句t3=t1+t2;
来调用重载方法。
但是o/p并不像预期的那样。o/p矩阵的结果与第二个矩阵相同。我不明白为什么。
这是代码。
#include<iostream>
using namespace std;
int m,n;
class test
{
int a[][10];
public:
void get()
{
cout<<"enter matrix elements"<<endl;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
cin>>a[i][j];
}
}
}
void print()
{
cout<<"matrix is as follows "<<endl;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
cout<<a[i][j]<<"t";
}
cout<<endl;
}
}
test operator + (test t2)
{
test temp;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
temp.a[i][j]=a[i][j]+t2.a[i][j];
}
}
return temp;
}
};
int main()
{
cout<<"enter value of m and n"<<endl;
cin>>m;
cin>>n;
test t1;
t1.get();
test t2;
t2.get();
t1.print();
t2.print();
test t3;
t3=t1+t2;
t3.print();
return 0;
}
o/p是---
G:>a.exe
enter value of m and n
2
2
enter matrix elements
1
1
1
1
enter matrix elements
2
2
2
2
matrix is as follows
2 2
2 2
matrix is as follows
2 2
2 2
third matrix is as follows
2 2
2 2
int a[][10];
这不是在分配一个合适的数组。我相信这会使一个大小为a[1][10]的数组,当你说时,你稍后会访问它
cin>>a[i][j];
和
cout<<a[i][j]<<"t";
用CCD_ 4;
您可能应该使用std::vector的std::vector,否则您需要使用new/delete自己分配动态内存。在c++中,不能在堆栈上创建动态大小的数组。
当你打开你发布的代码的警告/错误级别时,你可以在这里看到你应该得到的错误:
http://melpon.org/wandbox/permlink/AByJI3YnPijl6WYM
prog.cc:6:5: error: flexible array member 'a' in otherwise empty class is a GNU extension [-Werror,-Wgnu-empty-struct]
int a[][10];
^
prog.cc:6:5: error: flexible array members are a C99 feature [-Werror,-Wc99-extensions]
2 errors generated.
我也是编码新手,对C++不是很熟悉,但我并没有在代码中看到运算符重载。我只看到两个对象调用相同的类函数。对象(我认为)具有相同的值,所以输出是相同的
运算符重载类似于函数(int x),然后是另一个函数(int x,int y)。不同的参数,相同的函数名。
相关文章:
- 为什么我的代码在输出中增加了93天
- 为什么在C的循环中使用printf的Rust代码不显示输出,而在C++的循环中显示std::cout
- 在我的代码中,获得最大的Pair Wise产品C++和输出并不总是正确的
- 我无法获取以下代码的输出
- 为什么我的C++程序的程序集输出充满了 .ascii,没有汇编代码?
- 编译并运行后,输出未出现在 Visual Studio 代码中
- VI工作室代码错误无法打开输出文件主.exe
- 代码编译没有任何输出,入门程序
- 与其他编译器相比,相同的代码在工作室Microsoft提供不同的输出
- 可能我知道为什么这段代码没有给出任何输出吗?
- 从排序数组中删除重复项,具有不同代码方式的相同解决方案具有不同的输出
- Clang 给了我符号更改的警告,但代码仍然产生正确的输出
- 为什么这两个版本的代码给出不同的输出
- 以下与指针相关的代码的输出是什么?
- C++和 Python 中的代码相同,但输出不同
- 为什么我的代码块上没有显示输出?
- C++ 高级代码未给出正确的输出
- (C++)分解这个简单的输入/输出代码:
- 错误的输出代码
- 奇怪的输出(代码块codebblocks -16.01mingw-setup.exe)