【问题标题】:C++ Incomplete type is not allowed不允许 C++ 不完整类型
【发布时间】:2018-10-19 20:46:14
【问题描述】:

下面是我将用户名和密码写入文件的代码。除了 createUser() 函数之外,一切似乎都正常。

#include <iostream>
#include <stdio.h>
#include <string>
#include "login.h"
#include <fstream>

std::string user;
std::string pass;

struct Users {
    std::string username;
    std::string password;
};

void createUser(user, pass) {
    Users new;
    new.username = user;
    new.password = pass;
    ofstream inFile;
    inFile.open("users.txt");
    inFile << User.username << User.password;
    inFile.close()
}

int main(){
    createUser(Users.username, Users.password);
    return 0;
}

这里的错误是“不完整的类型是不允许的” 我假设它必须对我使用的结构做一些事情,但我不知道是什么。 它还说它需要一个“;”在第 15 行的 { 括号之后 (void createUser(){)

【问题讨论】:

  • 错字:不要使用new,这是一个保留字
  • 如果您在代码中使用了new 作为变量名,那可能是错误的来源,可能不是您在此处看到的错误
  • 如果您提供确切的错误信息,我可以尝试解释为什么您遇到了错误(从编译器复制粘贴)。
  • @Niko 试试std::ofstream。很多 C++ 的东西都存在于命名空间中。
  • @CoffeeTableEspresso 成功了,谢谢! (从现在开始将发布完整的错误消息)。

标签: c++


【解决方案1】:

你必须在 createUser 函数中声明类型:

void createUser(const std::string& user, const std::string& pass) {

【讨论】:

  • 它似乎奏效了,但你能解释一下为什么会发生这种情况吗?
  • @Niko C++ 是静态类型的,这意味着变量和函数的类型在编译时大部分是已知的,而不是在运行时,并且需要告诉编译器你打算使用的东西的类型,所以它可以编写正确的机器代码。例如x += y可以有非常不同的含义,当xy被允许为intdouble,std::string等时,编译器需要知道类型在为了让你的程序做正确的事情,因为类型信息在运行时基本上不存在。
猜你喜欢
  • 1970-01-01
  • 2016-05-08
  • 1970-01-01
  • 2019-10-08
  • 2011-05-13
  • 2011-08-12
  • 1970-01-01
  • 1970-01-01
  • 2015-10-09
相关资源
最近更新 更多