我尝试用Ada做的是创建一个Book对象,然后打印出那本书。问题是,语言不是很可写。当我编译,构建主文件,然后执行该文件时,它给了我这个错误:
raised CONSTRAINT_ERROR : book1.adb:28 length check failed
这是我在正文档中的内容:
package body Book1 is
function getAuthor (B: in Book) return AuthorName is
begin
return B.getAuthor;
end getAuthor;
function getTitle (B: in Book) return TitleName is
begin
return B.getTitle;
end getTitle;
function getNumberOfPages (B: in Book) return Pages is
begin
return B.getNumberOfPages;
end getNumberOfPages;
function createBook (Author: in String; Title: in String; NumberOfPages: in Float)
return Book is
B: Book;
begin
B.getAuthor := Author;
B.getTitle := Title;
B.getNumberOfPages := NumberOfPages;
return B;
end createBook;
end Book1;
这是我在spec文件中的内容:
package Book1 is
type Book is tagged private;
subtype AuthorName is String (1 .. 300);
subtype TitleName is String (1 .. 750);
subtype Pages is Float range 0.0 .. 5000000.0;
function getAuthor(B: in Book) return AuthorName;
function getTitle(B: in Book) return TitleName;
function getNumberOfPages(B: in Book) return Pages;
function createBook(Author: in String; Title: in String; NumberOfPages: in Float)
return Book;
private
type Book is tagged
record
getAuthor: AuthorName;
getTitle: TitleName;
getNumberOfPages: Pages;
end record;
end Book1;
这是我在测试文件中的内容:
with Book1, Ada.Text_IO, Ada.Float_Text_IO;
use Book1, Ada.Text_IO, Ada.Float_Text_IO;
procedure testBook is
theRealBook: Book := createBook(Author => "Jordan White",
Title => "The Last Christmas",
NumberOfPages => 32.0);
procedure Print_Book (B: in Book'Class) is
begin
Put (getAuthor (B => B));
Put (getTitle (B => B));
Put (getNumberOfPages (B => B));
New_Line;
end Print_Book;
begin
Print_Book (theRealBook);
end testBook;
我到底在做什么才能收到此错误,我该如何解决?
答案 0 :(得分:1)
你的陈述:
theRealBook: Book := createBook(Author => "Jordan White",
Title => "The Last Christmas",
NumberOfPages => 32.0);
作者和标题的字符串隐含长度(字符串文字)。 这意味着当您在此处分配作者和标题时:
B.getAuthor := Author;
B.getTitle := Title;
你正在假设" Jordan white"是一个长度为300的字符串。(标题相同的问题) 我怀疑这是作业,所以不好让你知道如何找到长度,字符串的边界,以及如何分配数组切片。