-1

我是 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){
 ^

有人可以帮我吗?非常感谢!

4

2 回答 2

4

您没有以分号结束类声明。这是正确的语法。

class ClassName { /* */ };

于 2013-09-22T19:54:37.740 回答
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可以用 aconst Imag&代替,而我们不需要#include <iostream>or using namespace std;realmake和private也是一个好主意imag,并引入 public reader 方法。

于 2013-09-22T20:15:08.223 回答