[SOLVED] Compile error when adding "const" to class method

已完成

For context, I'm fairly new to C++, CLion, and CMake.

Here are the steps that I'm taking:

  1. Create a new C++ executable project with C++14 language standard
  2. Enter the code below into main.cpp
  3. The code builds and runs with no errors
#include <iostream>
using namespace std;

class Person {
public:
void SayHello () {
cout << "Hello, World!";
}
};

int main() {
Person person;
person.SayHello();
return 0;
}

But then as soon as I add the keyword "const" after the method name like so:

void SayHello const () {

I'm getting the following compile errors:

[...]/main.cpp:6:10: error: field has incomplete type 'void'
void SayHello const () {
^
[...]/main.cpp:6:18: error: expected ';' at end of declaration list
void SayHello const () {
^
;
2 errors generated.

How can I fix this?

Thank you!

评论操作 固定链接

Ah, found my mistake! The "const" keyword was supposed to go after the round parentheses (doh).

0

请先登录再写评论。