//PROGRAM:
#include<iostream>
#include<conio.h>
using namespace std;
class complex {
private:
double re, img;
public:
complex();
void input();
complex SubCom(complex c1, complex c2);
complex SumCom(complex c1, complex c2);
complex MulCom(complex c1, complex c2);
void show();
};
complex::complex() {
re = 0;
img = 0;
}
void complex::input() {
cout << "Real:";
cin >> re;
cout << "Imagnary:";
cin >> img;
}
complex complex::SumCom(complex c1, complex c2) {
re = c1.re + c2.re;
img = c1.img + c2.img;
}
complex complex::SubCom(complex c1, complex c2) {
re = c1.re - c2.re;
img = c1.img - c2.img;
}
complex complex::MulCom(complex c1, complex c2)
{
re = c1.re * c2.re;
img = c1.img*c2.img;
}
void complex::show() {
cout << re << "," << img << "i";
}
int main() {
complex c1;
c1.input();
c1.show();
complex c2;
c2.input();
c2.show();
complex c;
c.SumCom(c1, c2);
c.show();
c.MulCom(c1, c2);
c.show();
c.SubCom(c1, c2);
c.show();
_getch();
return 0;
system("pause");
}
您好,我制作了一个程序,该程序使用作为类成员的函数将用户的整数转换为整数。我为 sum , product 和差异做了3个成员函数。现在显示的错误表明
1. complex::SumCom must return a value
2. complex::MulCom must return a value
3. complex::SubCom must return a value.
答案 0 :(得分:1)
这里
head
您已经保证返回一个complex SubCom(complex c1, complex c2);
^^^^^^^
complex SumCom(complex c1, complex c2);
^^^^^^^
complex MulCom(complex c1, complex c2);
^^^^^^^
,并且在您的任何成员函数定义中,您都没有返回它。这是 undefined behavior ,您很幸运VS给了您一个编译器错误。关于编译器错误,请尝试启用编译器警告,以查看并挽救自己在代码中的这种未定义行为。
解决方案是向您的成员函数添加一个看起来像(例如complex
应该是)的return语句
SumCom()
但是,我建议重载 +
, -
, *
operators
,因为这三个成员函数看起来像是完美的候选者。
这里是example code:
complex complex::SumCom(complex c1, complex c2)
{
// implementation
return /*resulting complex object*/;
}
标准输入:
#include<iostream>
class complex
{
private:
double re, img;
public:
complex() = default;
friend complex operator+(complex c1, const complex& c2) {
c1.re += c2.re;
c1.img += c2.img;
return c1;
}
friend complex operator-(complex c1, const complex& c2) {
c1.re -= c2.re;
c1.img -= c2.img;
return c1;
}
friend complex operator*(complex c1, const complex& c2) {
c1.re *= c2.re;
c1.img *= c2.img;
return c1;
}
void input();
void show();
};
void complex::input()
{
std::cout << "Real:" ; std::cin >> re;
std::cout << "Imaginary:" ; std::cin >> img;
}
void complex::show() {
std::cout << re << "," << img << "i\n";
}
int main()
{
complex c1;
c1.input();
c1.show();
complex c2;
c2.input();
c2.show();
complex c = c1 + c2; // now you can
c.show();
c = c1 * c2; // now you can
c.show();
c = c1 - c2; // now you can
c.show();
return 0;
}
输出:
Real:Imaginary:1,1i
Real:Imaginary:2,2i
答案 1 :(得分:0)
您必须写
return (object);
当您想返回一些值时。请记住,除非调用某些函数并将返回的值传递给它,否则您返回的值将不会显示在屏幕上(也许是控制台?)。