为什么下面的C++代码会给出这样的输出

Why the following C++ code gives this output?

本文关键字:输出 代码 C++ 为什么      更新时间:2023-10-16

我正在尝试在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)。不同的参数,相同的函数名。