简体   繁体   中英

Error: Constructor does not have return type and it says that variables x and y are undeclared

I have to create a template for two points ( x and y ). The compiler says that the variables are "undeclared identifiers" and I don't know why, but I already declared them in the constructor!!

I also get an error about the constructor not having a return type. What does that mean?

How can I fix these errors?

This is header code

#include <iostream>
#ifndef POINT_H
#define POINT_H

template <typename T>

class Point{

  private:

    T x;
    T y;

  public :

    Point(T x, T y);
    T getX();
    T getY();
    void setX(T xcoord);
    void setY(T ycoord);
    void print();
};

#endif

template <typename T>
T Point<T> :: Point(T x, T y){
  xcoord = x;
  ycoord = y;
}

template <typename T>
T Point<T> :: getX() {
  return x;
}

template <typename T>
T Point<T> :: getY(){
  return y;
}

template <typename T>
void T Point<T> :: setX( T xcoord){
  x = xcoord;
}

This is the main file

#include <iostream>
#include "point.h"
using namespace std;

int main(){
  Point<int> p1(3,5);
  p1.print();
  return 0;
}

Note that the code in the main file was commented out when the console was ran. These errors come only from the header file

Errors:

Variable T from setx constructor has incomplete type <void> , expected ";"

unknown type "T"

extra member qualification on member "setx"

undeclared use of identifier "x"

图片

template <typename T>
T Point<T> :: Point(T x, T y){
  xcoord = x;
  ycoord = y;
}

should be (CORRECTED)

template <typename T>
Point<T> :: Point(T x, T y){
  this->x = x;
  this->y = y;
}

Constructors don't have return types (as the error says), and xcoord and ycoord are not members of your class.

also

template <typename T>
void T Point<T> :: setX( T xcoord) {
  x = xcoord;
}

should be

template <typename T>
void Point<T> :: setX( T xcoord) {
  x = xcoord;
}

void T is not a valid type.

If you get multiple errors, always start to fix the first one first. The later errors much too often are caused by the compiler misunderstanding everything after the first error. The error you describe are irrelevant.

For fixing the first error you need to decide whether you want a return value of type void (ie no return value) or of type T. For a setter method, I think void is appropriate, so simply delete the T, which matches the declaration inside the class.

This (as you confirmed in a comment) fixes the first of the errors and because of the otherwise implausible and inconsistent question I consider this to be the core of the question. Please create a new question on how to implement a constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM