我是C ++的新手,我正在编写一个程序来添加两个复数:
这是我的.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
这是我的.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;
}
编译时,它抱怨如下:
imagine.cpp:5:1: error: ‘Imag’ does not name a type
Imag::Imag(){
^
imagine.cpp:10:1: error: ‘Imag’ does not name a type
Imag Imag:: add(Imag i){
^
有人可以帮我这个吗?非常感谢!
答案 0 :(得分:4)
你没有用分号结束类声明。这是正确的语法。
class ClassName { /* */ };
答案 1 :(得分:0)
我无法重现问题,我得到了不同的错误:
$ 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
可能需要const Imag&
,而我们不需要#include <iostream>
或using namespace std;
。将real
和imag
设为私有,并引入公共读者方法也是一个好主意。