当我调用 main 中使用 const 对象的 const 函数时,不断出现错误

keep getting error when i call a const function with a const object in main

本文关键字:const 错误 函数 对象 main 调用      更新时间:2023-10-16

头文件:

#ifndef CONTMEM_H
#define CONTMEM_H
class Contmem {
public:
Contmem(int a, int b, int c);
int total;
int mem;
const int constmem;
int printconst() const;
const int constant;
void print();
};
#endif // CONTMEM_H

Contmem.cpp file:

#include "Contmem.h"
#include <iostream> 
Contmem::Contmem(int a, int b, int c)
: mem(a), constmem(b), constant(c)
{
total = mem * constmem * constant;
}
void Contmem::print()
{
std::cout << "This is my variable member " << mem << " and this is my constmem member " << constmem << "with the constant member" << constant << std::endl;  
}
int  Contmem::printconst() const
{
return total;
std::cout << "This is the total variable " << total << std::endl;
}

主要功能:

#include <iostream>
#include "Contmem.h"
int main()
{
Contmem cont(3, 4, 5);
cont.print();
const Contmem obj;
obj.printconst();
}

错误文件:

|=== Build: Debug in CONST_&_MEMBER_INITIALIZER
(compiler: GNU GCC Compiler) ===| C:C++
CODEBLOCKCONST_&_MEMBER_INITIALIZERmain.cpp||
In function 'int  main()':| C:C++
CODEBLOCKCONST_&_MEMBER_INITIALIZERmain.cpp|9|error: 
no matching function for call to 'Contmem::Contmem()'| 
C:C++  CODEBLOCKCONST_&_MEMBER_INITIALIZERContmem.h|8|note: candidate:
Contmem::Contmem(int, int, int)| C:C++
CODEBLOCKCONST_&_MEMBER_INITIALIZERContmem.h|8|note:   candidate
expects 3 arguments, 0 provided| C:C++
CODEBLOCKCONST_&_MEMBER_INITIALIZERContmem.h|5|note: candidate:
Contmem::Contmem(const Contmem&)| C:C++
CODEBLOCKCONST_&_MEMBER_INITIALIZERContmem.h|5|note:   candidate
expects 1 argument, 0 provided| ||=== Build failed: 1 error(s), 0
warning(s) (0 minute(s), 0 second(s)) ===|

缺少类的默认构造函数。你只有这个

Contmem::Contmem(int a, int b, int c)
: mem(a), constmem(b), constant(c)
{
total = mem * constmem * constant;
}

但在这里

int main()
{
Contmem cont(3, 4, 5);
cont.print();
const Contmem obj; // <--here
obj.printconst();
}

您正在尝试在不传递这 3 个参数的情况下构造一个新的Contmem对象


实际上,这些编译器错误告诉您真正的问题是什么。

const Contmem obj;

尝试调用默认构造函数Contmem()

因为:

Contmem::Contmem(int a, int b, int c)
: mem(a), constmem(b), constant(c)

具有 mem 初始值设定项和const成员,则默认构造函数被删除

因此,编译器无法将该语句与任何现有构造函数匹配,因为仅存在 mem 初始值设定项构造函数。

相关文章: