我无法重现该问题,我得到不同的错误:
$ cat imagine.h
#ifndef IMAGINE_H
#define IMAGINE_H
#include<iostream>
using std::ostream;
class Imag{
public:
double real;
double imag;
Imag() = default;
Imag(double,double);
Imag add(Imag);
};
#endif
$ cat imagine.cpp
#include<iostream>
#include"imagine.h"
using namespace std;
Imag::Imag(){
this-> real;
this-> imag;
}
Imag Imag:: add(Imag i){
Imag result = new Image();
result -> real = this->real + i -> real;
result -> imag = this-> imag + i-> imag;
return result;
}
$ g++ -c -W -Wall -s -O2 imagine.cpp
In file included from imagine.cpp:2:
imagine.h:12: warning: defaulted and deleted functions only available with -std=c++0x or -std=gnu++0x
imagine.cpp: In constructor ‘Imag::Imag()’:
imagine.cpp:6: warning: statement has no effect
imagine.cpp:7: warning: statement has no effect
imagine.cpp: In member function ‘Imag Imag::add(Imag)’:
imagine.cpp:11: error: expected type-specifier before ‘Image’
imagine.cpp:11: error: conversion from ‘int*’ to non-scalar type ‘Imag’ requested
imagine.cpp:11: error: expected ‘,’ or ‘;’ before ‘Image’
imagine.cpp:12: error: base operand of ‘->’ has non-pointer type ‘Imag’
imagine.cpp:12: error: base operand of ‘->’ has non-pointer type ‘Imag’
imagine.cpp:13: error: base operand of ‘->’ has non-pointer type ‘Imag’
imagine.cpp:13: error: base operand of ‘->’ has non-pointer type ‘Imag’
以下是修复它们的方法:
$ cat imagine.h
#ifndef IMAGINE_H
#define IMAGINE_H
#include<iostream>
using std::ostream;
class Imag{
public:
double real;
double imag;
Imag();
Imag(double,double);
Imag add(Imag);
};
#endif
$ cat imagine.cpp
#include<iostream>
#include"imagine.h"
using namespace std;
Imag::Imag(): real(0), imag(0) {}
Imag::Imag(double r, double i): real(r), imag(i) {}
Imag Imag::add(Imag i){
Imag result;
result.real = real + i.real;
result.imag = imag + i.imag;
return result;
}
$ g++ -c -W -Wall -s -O2 imagine.cpp
(No errors or warnings.)
还有很多其他方法可以改进代码,例如add
可以用 aconst Imag&
代替,而我们不需要#include <iostream>
or using namespace std;
。real
make和private也是一个好主意imag
,并引入 public reader 方法。